package com.hanzhong.travel.controller;

import com.hanzhong.travel.entity.Food;
import com.hanzhong.travel.service.FoodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 美食控制器
 */
@RestController
@RequestMapping("/api/foods")
public class FoodController {

    @Autowired
    private FoodService foodService;
    
    /**
     * 添加美食
     */
    @PostMapping
    public ResponseEntity<?> addFood(@RequestBody Food food) {
        System.out.println("收到添加美食请求: " + food.getName());
        boolean success = foodService.addFood(food);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "美食添加成功");
            result.put("data", food);
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body("美食添加失败");
        }
    }
    
    /**
     * 获取所有美食
     */
    @GetMapping
    public ResponseEntity<?> getAllFoods() {
        System.out.println("收到获取所有美食请求");
        List<Food> foods = foodService.getAllFoods();
        return ResponseEntity.ok(foods);
    }
    
    /**
     * 根据分类获取美食
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<?> getFoodsByCategory(@PathVariable String category) {
        System.out.println("收到按分类获取美食请求: category=" + category);
        List<Food> foods = foodService.getFoodsByCategory(category);
        return ResponseEntity.ok(foods);
    }
    
    /**
     * 分页获取美食
     */
    @GetMapping("/page")
    public ResponseEntity<?> getFoodsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        System.out.println("收到分页获取美食请求: page=" + page + ", size=" + size);
        Map<String, Object> result = foodService.getFoodsByPage(page, size);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 根据ID获取美食
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getFoodById(@PathVariable Long id) {
        System.out.println("收到获取美食详情请求: " + id);
        Food food = foodService.getFoodById(id);
        if (food != null) {
            return ResponseEntity.ok(food);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 更新美食
     */
    @PutMapping("/{id}")
    public ResponseEntity<?> updateFood(@PathVariable Long id, @RequestBody Food food) {
        System.out.println("收到更新美食请求: " + id);
        food.setId(id);
        boolean success = foodService.updateFood(food);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "美食更新成功");
            result.put("data", food);
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body("美食更新失败");
        }
    }
    
    /**
     * 删除美食
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteFood(@PathVariable Long id) {
        System.out.println("收到删除美食请求: " + id);
        boolean success = foodService.deleteFood(id);
        if (success) {
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "美食删除成功");
            return ResponseEntity.ok(result);
        } else {
            return ResponseEntity.badRequest().body("美食删除失败");
        }
    }
    
    /**
     * 上传美食图片
     */
    @PostMapping("/upload")
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {
        System.out.println("收到上传美食图片请求");
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择文件");
        }

        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 生成新文件名
            String newFileName = UUID.randomUUID().toString() + 
                    fileName.substring(fileName.lastIndexOf("."));
            
            // 确定文件存储路径
            String uploadDir = "uploads/foods/";
            Path uploadPath = Paths.get(uploadDir);
            
            // 如果目录不存在，创建目录
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            
            // 保存文件
            Path filePath = Paths.get(uploadDir + newFileName);
            Files.write(filePath, file.getBytes());
            
            // 返回文件访问路径
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "文件上传成功");
            result.put("url", "/uploads/foods/" + newFileName);
            
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }
} 